import router from './router'
const Router = router
// 引入store实例
import store from './store'
// 引入本地存储
import storage from 'store'
// 加载进度条
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
// 本地存储key值
import {ACCESS_TOKEN, ROLE_ADMIN, SELECTED_ORG} from '@/store/mutation-types'
import { i18nRender } from '@/locales'

import { timeFix } from '@/utils/util'
import { resetRouter } from '@/router/index'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const allowList = ['login', 'publicReport'] // 登录页在免登录里
const loginRoutePath = '/login/login'
const defaultRoutePath = '/workplace'

Router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`))
  /* has token */
  /* 判断是否能获取到token */
  if (storage.get(ACCESS_TOKEN)) {
    // 如果跳转页为登录页，则跳转默认页
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
      NProgress.done()
    }else if (to.path === defaultRoutePath && to.params && to.params.event === 'changeOrg'){
      buildMenu(false)
      next()
    } else {
      // 如果getters里没有角色就去获取角色
      if (store.getters.roles.length === 0) {
        // request login userInfo
        buildMenu(true, {to:to, from:from, next:next})
      } else {
        next()
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } });
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

function filterAsyncRouter (routerMap) {
  let accessedRouters = []
  if (routerMap.length) {
    accessedRouters = routerMap.map(route => {
        return renderRoute(route)
    })

  }
  return accessedRouters
}

function renderRoute (route) {
  const currentRoute = {
    path:'/blank_view/' + route.id,
    name: route.name + route.id,
    meta: { title: route.name ? route.name : '未设置', id: route.reportId },
    component: () => import('@/views/reportForms/showReports'),
  }

  if (route.children) {
    currentRoute.meta.icon = 'dashboard'
  }

  if (route.children && route.children.length) {
    currentRoute.children = filterAsyncRouter(route.children)
  }
  return currentRoute
}

function buildMenu(redirectFLag, routerObj) {
  store
    .dispatch('GetInfo')
    .then(res => {
      const result = res.data
      const authorities = {
        roleList: [],
        permissionList: [],
      }
      if(result.roles && result.roles.length > 0) {
        authorities.roleList = result.roles
        if(result.permissions && result.permissions.length > 0) {
          authorities.permissionList = result.permissions
        }
      }
      if (authorities.roleList.find(ele => ele === 'administrator')){
        store.commit('SET_ORGS', [])
      }else if (result.orgs && result.orgs.length > 0){
        store.commit('SET_ORGS', result.orgs)
        const stored_org = storage.get(SELECTED_ORG)
        if (stored_org && stored_org.id !== null){
          const has_org = result.orgs.filter(item => {
            if(item.id === stored_org.id){
              return true
            }
          })
          if (has_org){
            store.commit('SET_ORG',stored_org)
          }else {
            storage.set(SELECTED_ORG,result.orgs[0])
            store.commit('SET_ORG',result.orgs[0])
          }
        }else {
          storage.set(SELECTED_ORG,result.orgs[0])
          store.commit('SET_ORG',result.orgs[0])
        }
      }
      /**
       * 添加用户菜单
       */
       /*
      store.dispatch('GetMenu').then(res=>{
        const custom_menu = res.data || []
        const accessedRouters = filterAsyncRouter(custom_menu);
        store.dispatch('GenerateRoutes', { roles: authorities, menu: accessedRouters }).then(() => {
          resetRouter()
          const asyncRoutes = store.getters.addRouters;
          Router.addRoutes(asyncRoutes)
          if (redirectFLag){
            const redirect = decodeURIComponent(routerObj.from.query.redirect || routerObj.to.path);
            if (routerObj.to.path === redirect) {
              //
              routerObj.next({ ...routerObj.to, replace: true })
            } else {
              // 跳转到目的路由
              routerObj.next({ path: redirect })
            }
          }
        })
      })
      */
      // store.dispatch('GetUserStyle')
      const custom_menu = []
      const accessedRouters = filterAsyncRouter(custom_menu);
      store.dispatch('GenerateRoutes', { roles: authorities, menu: accessedRouters }).then(() => {
        resetRouter()
        const asyncRoutes = store.getters.addRouters;
        Router.addRoutes(asyncRoutes)
        if (redirectFLag){
          const redirect = decodeURIComponent(routerObj.from.query.redirect || routerObj.to.path);
          if (routerObj.to.path === redirect) {
            //
            routerObj.next({ ...routerObj.to, replace: true })
          } else {
            // 跳转到目的路由
            routerObj.next({ path: redirect })
          }
        }
      })
    })
    .catch((err) => {
      console.log(err)
      notification.error({
        message: '错误',
        description: '请求用户信息失败，请重试'
      })
      store.dispatch('Logout').then(() => {
        routerObj.next({ path: loginRoutePath, query: { redirect: routerObj.to.fullPath } })
      })
    })
}


Router.afterEach(() => {
  NProgress.done() // finish progress bar
})
